#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
int a,b;
int ans = INF;
int vis[10000];
int step[10000];

int judge(int n){
	if(n == 1) return false;
	if(!(n & 1)) return false;
	for(int i = 2;i * i <= n;i++){
		if(n % i == 0) return false;
	}
	return true;
}
int bfs(){
	memset(vis,0,sizeof(vis));
	memset(step,0,sizeof(step));
	queue<int> q;
	int node = a;
	q.push(node);
	vis[node] = 1;
	step[node] = 0;
	ans = INF;
	int cnt = 0;
	while(!q.empty()){
		node = q.front();
		q.pop();
		if(node == b){
			ans = min(ans,step[node]);
			return ans;
		}
		for(int i = 1;i <= 4;i++){
			for(int j = 0;j <= 9;j++){
				if(i == 1 && j == 0) continue;
				int thou = node / 1000;
				int hand = (node - 1000 * thou) / 100;
				int shi = (node - (node / 100) * 100) / 10;
				int ge = node % 10;
				if(i == 1){
					thou = j;
				}else if(i == 2){
					hand = j;
				}else if(i == 3){
					shi = j;
				}else if(i == 4){
					ge = j;
				}
				int next = thou * 1000 + hand * 100 + shi * 10 + ge * 1;
				
				if(!judge(next) || vis[next] || next <= 1000){
					continue;
				}
				vis[next] = 1;
				step[next] = step[node] + 1;
				q.push(next);
				
			}
		}
	}
}
int main(){
	int t;
	cin >> t;
	while(t--){
		cin >> a >> b;
		bfs();
		if(ans != INF)
			cout << ans << "\n";
		else cout << "IMPOSSIBLE\n";
	}
}